<template>
  <div>
    <a-modal
        :title="currTitle()"
        :visible="visible"
        @cancel="showModel(false)"
    >
      <template>
        <div class="table-operator" style="width: 20%; min-width: 400px">
          <a-form :form="form" @submit="handleSubmit">
            <!--        最大连接数-->
            <a-form-item
                v-bind="formItemLayout"
                label="同时登录数量限制"
            >
              <a-input
                  v-decorator="[`loginAtTheSameTime`, validatorRules.count]"
                  placeholder="请输入 1 到 100 的整数"
                  style="width: 80%; margin-right: 8px"
              />
            </a-form-item>
            <!--        启用IP绑定按钮-->
            <a-form-item
                v-bind="formItemLayout"
                label="启用IP绑定"
            >
              <a-switch
                  v-decorator="[
                  `loginIpWhiteListOnOff`,{
                    // 绑定子节点的属性值
                    valuePropName: 'checked',
                    // 给子节点一个默认值
                    initialValue: true
                  }]"
                  checked-children="开"
                  un-checked-children="关"
                  @click="btnClicked"/>
            </a-form-item>
            <!--        IP地址输入列表-->
            <div v-if="btnChecked">
              <a-form-item
                  v-for="(k, index) in form.getFieldValue('keys')"
                  :key="k"
                  v-bind="index === 0 ? formItemLayout : formItemLayoutWithOutLabel"
                  :label="index === 0 ? 'IP地址绑定' : ''"
                  :required="false"
              >
                <a-input
                    v-decorator="[`loginIpWhiteList[${k}]`, validatorRules.ip]"
                    placeholder="请输入需要绑定的IP地址"
                    style="width: 80%; margin-right: 8px"
                />
                <a-icon
                    class="dynamic-delete-button"
                    type="minus-circle-o"
                    @click="() => remove(k)"
                />
              </a-form-item>
              <a-form-item v-bind="formItemLayoutWithOutLabel">
                <a-button type="dashed" style="width: 80%" @click="add">
                  <a-icon type="plus" /> 添加绑定输入项
                </a-button>
              </a-form-item>
            </div>
<!--            <a-form-item v-bind="formItemLayoutWithOutLabel">-->
<!--              <a-button type="primary" html-type="submit">-->
<!--                提交-->
<!--              </a-button>-->
<!--            </a-form-item>-->
          </a-form>
        </div>
      </template>
      <template slot="footer">
        <a-button type="primary" html-type="submit" @click="handleSubmit">提交</a-button>
        <a-button @click="showModel(false)">关闭</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import {
  getAction,
  postAction
} from '@/api/manage'

let id = 0;
export default {
  name: "UserLoginConfigModal",
  data() {
    return {
      userName:"",
      userID: "",
      visible: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 16, offset: 8 },
        },
      },
      validatorRules: {
        count:{
          validateTrigger: ['change', 'blur'],
          rules: [{
            required: true,
            whitespace: true,
            pattern: /^([1-9][0-9]{0,1}|100)$/,
            message: '请输入1-100的整数!'
          }],
        },
        ip:{
          validateTrigger: ['change', 'blur'],
          rules: [{
            required: true,
            whitespace: true,
            // pattern:/^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$/,
            pattern: /^(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){2}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/,
            message: '请输入正确的IP地址 或 删除此项!'
          }],
        },
      },
      btnChecked: true,
      ipList:[],
      url:{
        getParam: "/sys/user/user-login-config",
        setParam: "/sys/user/save-login-config"
      }
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'sys_param_set' });
    this.form.getFieldDecorator('keys', { initialValue: [], preserve: true });
  },
  mounted() {
    console.log('---------------------------------------');
  },
  methods: {
    currTitle() {
      let str = '[ ' + this.userName + ' ]的登录配置'
      return str;
    },
    showModel(visible) {
      this.visible = visible;
      if (this.userID.length !== 0) {
        this.getData();
      }
    },
    getData() {
      this.clearViewData();
      let that = this;
      getAction(that.url.getParam + '/' + this.userID).then((res) => {
        if (res.code === "00000") {
          // console.log(res)
          for (let i=0; i<res.data.loginIpWhiteList.length; i++) {
            this.add()
          }
          this.btnChecked = true
          if (res.data.loginIpWhiteListOnOff === 'off') {
            this.btnChecked = false
          }
          this.form.setFieldsValue({
            loginAtTheSameTime: res.data.loginAtTheSameTime,
            loginIpWhiteListOnOff: this.btnChecked,
          })
          that.ipList = res.data.loginIpWhiteList;
          if (this.btnChecked) {
            this.$nextTick(() => {
              this.form.setFieldsValue({
                loginIpWhiteList: that.ipList,
              })});
          }
        }
        else {
          that.$message.warning("获取系统参数:" + res.msg)
          that.ipList = [];
        }
      });
    },
    setUserID(userid, username){
      this.userID = userid;
      this.userName = username;
    },
    remove(k) {
      const { form } = this;
      // can use data-binding to get
      const keys = form.getFieldValue('keys');

      // can use data-binding to set
      form.setFieldsValue({
        keys: keys.filter(key => key !== k),
      });
    },

    clearViewData() {
      id = 0;
      this.form.setFieldsValue({
        keys:[],
        loginIpWhiteList:[],
      });
    },
    add() {
      const { form } = this;
      // can use data-binding to get
      const keys = form.getFieldValue('keys');
      const nextKeys = keys.concat(id++);
      // can use data-binding to set
      // important! notify form to detect changes
      form.setFieldsValue({
        keys: nextKeys,
      });
    },

    handleSubmit() {
      let that = this;
      this.form.validateFields((err, values) => {
        if (!err) {
          // const { keys, names } = values;
          console.log('Received values of form: ', values);
          if (values.keys) {
            delete values.keys;
          }
          if (!('loginIpWhiteList' in values)) {
            values.loginIpWhiteList = this.ipList;
          }
          values.loginAtTheSameTime = Number(values.loginAtTheSameTime)
          values.loginIpWhiteListOnOff = that.btnChecked ? "on":"off";
          values.userId = this.userID;
          console.log('values of form: ', values);
          postAction(this.url.setParam, values).then((res) => {
            if (res.code == "00000") {
              that.$message.success("系统参数设置成功")
              that.ipList = values.loginIpWhiteList;
            } else {
              that.$message.warning("系统参数设置失败:" + res.msg)
            }
          })
        }
      });
    },

    validateIp() {
      return false;
    },
    btnClicked(checked) {
      this.btnChecked = checked;
      if (this.btnChecked) {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            loginIpWhiteList: this.ipList,
          })});
      }
    },
  },
};
</script>
<style>
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>